package com.hq.ims.userpc.busservice;

import com.hq.authority.utils.AppUtils;
import com.hq.ims.data.config.verification.VdAdd;
import com.hq.ims.data.config.verification.VdEdit;
import com.hq.ims.data.entity.*;
import com.hq.ims.data.entityenum.EnumAuditStatus;
import com.hq.ims.data.entityenum.EnumBusinessTypeStatus;
import com.hq.ims.data.entityenum.EnumFeedbackPhase;
import com.hq.ims.data.service.*;
import com.hq.ims.data.utils.ErrMsgConstant;
import com.hq.ims.data.utils.LocalConstant;
import com.hq.ims.data.utils.WebExpandUtils;
import com.hq.ims.data.vo.*;
import com.hq.utils.util.BooleanUtils;
import com.hq.utils.util.ObjectUtils;
import com.hq.web.utils.SpringBootValidateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yinzhangxiao
 * @date 2024/10/31 9:43
 * @ClassName ProjectFilingService
 **/
@Service
public class ProjectFilingService {
    @Resource
    private BaseBusiInfoService baseBusiInfoService;
    @Resource
    private BaseBusiIndustryAssignService baseBusiIndustryAssignService;
    @Resource
    private BaseBusInfoTrackService baseBusInfoTrackService;
    @Resource
    private BaseCompanyService baseCompanyService;
    @Resource
    private BaseBusiHistoryService baseBusiHistoryService;
    @Resource
    private BaseBusInfoFeedbackService baseBusInfoFeedbackService;

    /**
     * @description: 线下备案新增
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:45
     */
    @Transactional(rollbackFor = Exception.class)
    public void addBusiInfo(BusiInfoMapstruct.SaveVo vo) {
        //验证数据是否为空
        SpringBootValidateUtils.validate(vo, VdAdd.class);
        vo.setInfoType(EnumBusinessTypeStatus.ExternalStatement);
        //校验数据
        baseBusiInfoService.validate(null,vo, LocalConstant.INSERT);
        //查询省市code
        baseBusiInfoService.setAreaCode(vo);
        //补全数据
        vo.setAuditStatus(EnumAuditStatus.UnderReview);
        vo.setOrgId(WebExpandUtils.getHeadCompanyId());
        vo.setPublishTime(LocalDateTime.now());
        vo.setPublisherId(AppUtils.getUserId());
        vo.setPublisher(AppUtils.getCurrentUser().getRealName());
        vo.setContactPerson(AppUtils.getCurrentUser().getRealName());
        vo.setContactInfomation(AppUtils.getCurrentUser().getMobile());
        vo.setParentId("0");
        //根据选择的产业标记拼接产业标记字段
        baseBusiInfoService.setBusiIndustryAssign(vo);
        BusiInfo busiInfo = baseBusiInfoService.addData(vo);
        vo.setBusiInfoId(busiInfo.getBusiInfoId());
        //计算重复率
        BigDecimal repetitionRate = baseBusiInfoService.calcSimilarityRate(vo);
        busiInfo.setRepetitionRate(repetitionRate.setScale(0, RoundingMode.HALF_UP).doubleValue());
        busiInfo.setVersion(0);
        busiInfo.setRootId(busiInfo.getRootId());
        baseBusiInfoService.updateById(busiInfo);
        //插入历史表
        BusiHistoryMapstruct.SaveVo build = new BusiHistoryMapstruct.SaveVo();
        BeanUtils.copyProperties(busiInfo, build);
        baseBusiHistoryService.addData(build);
        //更新产业标记
        vo.getBusiIndustryAssignList().forEach(d -> d.setBusiInfoId(vo.getBusiInfoId()));
        baseBusiIndustryAssignService.updateDataBatch(vo.getBusiIndustryAssignList());
        //指派经营人员
        vo.getBusiIndustryAssignList().forEach(this::saveBaseBusInfoTrack);
    }

    /**
     * @description: 线下备案修改
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:45
     */
    @Transactional(rollbackFor = Exception.class)
    public void editBusiInfo(BusiInfoMapstruct.SaveVo vo) {
        //验证数据是否为空
        SpringBootValidateUtils.validate(vo, VdEdit.class);
        vo.setInfoType(EnumBusinessTypeStatus.ExternalStatement);
        //验证数据是否存在
        BusiInfo entity = baseBusiInfoService.getById(vo.getBusiInfoId());
        ObjectUtils.isNullThrow(entity, ErrMsgConstant.PROJECT_INFO_NOT_EXITS);
        //校验数据
        baseBusiInfoService.validate(entity,vo,LocalConstant.EDIT);
        //查询省市code
        baseBusiInfoService.setAreaCode(vo);
        //拼接信息表产业标记字段
        baseBusiInfoService.setBusiIndustryAssign(vo);
        vo.setUpdateDateTime(LocalDateTime.now());
        vo.setUpdateUserName(AppUtils.getCurrentUser().getRealName());
        BusiInfo busiInfo = baseBusiInfoService.editData(vo);
        //更新产业标记
        //比对产业标记以及经营人员
        List<BusInfoTrack> trackList = baseBusInfoTrackService.lambdaQuery()
                .eq(BusInfoTrack::getBusiInfoId, vo.getBusiInfoId())
                .list();
        List<BusiIndustryAssignMapstruct.SaveVo> busiIndustryAssignList = vo.getBusiIndustryAssignList();
        //需删除的跟踪信息集合
        List<BusInfoTrack> deletTrackList = new ArrayList<>();
        for (BusInfoTrack busInfoTrack : trackList) {
            boolean flag = true;
            //当变更数据集合中不包含原始产业标记或者经营人员有变化则添加到需要删除的数组中
            for (BusiIndustryAssignMapstruct.SaveVo saveVo : busiIndustryAssignList) {
                if (busInfoTrack.getBusInfoTrackId().equals(saveVo.getIndustryId())) {
                    if (busInfoTrack.getBusiPersonId().equals(saveVo.getBusInfoTrack().getBusiPersonId())) {
                        flag = false;
                    }
                }
            }
            if (flag) {
                deletTrackList.add(busInfoTrack);
            }
        }
        //删除有变化的产业标记、跟踪信息、反馈信息
        if (CollectionUtils.isNotEmpty(deletTrackList)) {
            //删除产业标记
            baseBusiIndustryAssignService.lambdaUpdate().in(
                    BusiIndustryAssign::getIndustryId,
                    deletTrackList.stream().map(BusInfoTrack::getIndustryMarkId).collect(Collectors.toList())
            ).remove();
            //删除经营信息跟踪信息
            baseBusInfoTrackService.lambdaUpdate().in(
                    BusInfoTrack::getBusInfoTrackId,
                    deletTrackList.stream().map(BusInfoTrack::getBusInfoTrackId).collect(Collectors.toList())
            ).remove();
            //删除经营信息反馈信息
            baseBusInfoFeedbackService.lambdaUpdate().in(
                    BusInfoFeedback::getBusInfoTrackId,
                    deletTrackList.stream().map(BusInfoTrack::getBusInfoTrackId).collect(Collectors.toList())
            ).remove();
        }
        //插入新增和改变的
        List<BusiIndustryAssignMapstruct.SaveVo> addBusiIndustryAssignList = new ArrayList<>();
        for (BusiIndustryAssignMapstruct.SaveVo saveVo : busiIndustryAssignList) {
            boolean flag = true;
            //当原始数据集合中不包含原始产业标记或者经营人员有变化则添加到需要新增的数组中
            for (BusInfoTrack busInfoTrack : trackList) {
                if (busInfoTrack.getIndustryMarkId().equals(saveVo.getIndustryId())) {
                    if (busInfoTrack.getBusiPersonId().equals(saveVo.getBusInfoTrack().getBusiPersonId())) {
                        flag = false;
                    }
                }
            }
            if (flag) {
                addBusiIndustryAssignList.add(saveVo);
            }
        }
        //插入新增的（变化的）产业标记、跟踪信息
        if (CollectionUtils.isNotEmpty(addBusiIndustryAssignList)) {
            for (BusiIndustryAssignMapstruct.SaveVo assign : addBusiIndustryAssignList) {
                //插入产业标记
                assign.setBusiInfoId(vo.getBusiInfoId());
                baseBusiIndustryAssignService.addData(assign);
                //指派经营人员
                saveBaseBusInfoTrack(assign);
            }
        }
        //插入信息变更历史
        baseBusiHistoryService.saveBusiChangeTimeRecord(busiInfo);
    }

    /**
     * @description: 线下备案批量删除
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:46
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataBatch(List<String> busiInfoIds) {
        for (String busiInfoId : busiInfoIds) {
            BusiInfo busiInfo = baseBusiInfoService.getById(busiInfoId);
            if (ObjectUtils.isNull(busiInfo)) {
                continue;
            }
            //验证是否存在派生信息
            Boolean deriveFlag = baseBusiInfoService.lambdaQuery().eq(BusiInfo::getParentId, busiInfoId).count() > 0;
            BooleanUtils.isTrueThrow(deriveFlag, "项目名称：" + busiInfo.getProjectName() + ",已创建派生信息不允许变更删除!");
            baseBusiInfoService.removeById(busiInfoId);
            //删除经营信息跟踪信息
            baseBusInfoTrackService.lambdaUpdate().eq(BusInfoTrack::getBusiInfoId, busiInfoId).remove();
            //删除经营信息反馈信息
            baseBusInfoFeedbackService.lambdaUpdate().eq(BusInfoFeedback::getBusiInfoId, busiInfoId).remove();
        }
    }

    /**
     * @description: 指派经营人员
     * @author: yinzhangxiao
     * @date: 2024/11/15 14:46
     */
    private void saveBaseBusInfoTrack(BusiIndustryAssignMapstruct.SaveVo busiIndustryAssign) {
        if (busiIndustryAssign.getBusInfoTrack() != null) {
            BusInfoTrack busInfoTrack = busiIndustryAssign.getBusInfoTrack();
            busInfoTrack.setIndustryMarkId(busiIndustryAssign.getIndustryId());
            busInfoTrack.setIndustryMarkName(busiIndustryAssign.getIndustryName());
            busInfoTrack.setBusiInfoId(busiIndustryAssign.getBusiInfoId());
            busInfoTrack.setCompanyId(WebExpandUtils.getHeadCompanyId());
            busInfoTrack.setOrgId(WebExpandUtils.getHeadCompanyId());
            busInfoTrack.setLastNewFeedbackPhase(EnumFeedbackPhase.ProjectNotDiscussed);
            busInfoTrack.setLastNewFeedbackDate(LocalDateTime.now());
            Company company = baseCompanyService.lambdaQuery().eq(Company::getCompanyId, busInfoTrack.getCompanyId()).one();
            busInfoTrack.setCompanyName(ObjectUtils.isNotNull(company) ? company.getCompanyName() : "");
            baseBusInfoTrackService.save(busiIndustryAssign.getBusInfoTrack());
        }
    }
}
